<script setup>
import { ref,watch } from 'vue'
import { addSongList } from '@/api/song-list'
import ImageUpload from '@/components/ImageUpload.vue' 
import Singer from '@/views/singer/Singer.vue'


const visible = ref(false)
const isEdit = ref(false)

// 表单数据
const form = ref({
  id: null,
  title: '',
  style: '',
  pic: '', 
  introduction: ''
})

// 打开抽屉的方法（支持传入歌单数据进行编辑）
const openDrawer = (songList = null) => {
  visible.value = true
  if (songList) {
    isEdit.value = true
    form.value = {
      id: songList.id || null,
      title: songList.title || '',
      style: songList.style || '',
      pic: songList.pic || '', // 图片路径
      introduction: songList.introduction || ''
    }
  } else {
    isEdit.value = false
    resetForm()
  }
}

// 上传成功回调
const upload = (url) => {
  form.value.pic = url
}

// 提交表单
const submitForm = async () => {
  try {
    const res = await addSongList(form.value)
    ElMessage.success(res.msg || (isEdit.value ? '更新成功' : '添加成功'))
    visible.value = false
    if (typeof window.fetchPlaylists === 'function') {
      window.fetchPlaylists()
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '操作失败')
  }
  emit('saved')
}
const emit = defineEmits(['saved'])
// 重置表单
const resetForm = () => {
  form.value = {
    id: null,
    title: '',
    style: '',
    pic: '',
    introduction: ''
  }
}

defineExpose({ openDrawer })


</script>

<template>
  <el-drawer v-model="visible" title="新建歌单" size="40%">
    <el-form label-width="auto" style="padding: 20px">
      <el-form-item label="歌单名称">
        <el-input v-model="form.title" />
      </el-form-item>
      <el-form-item label="风格类型">
        <el-input v-model="form.style" />
      </el-form-item>
      <el-form-item label="封面图片">
        <image-upload @upload-success="upload" />
      </el-form-item>
      <el-button type="primary" @click="submitForm" block>提交</el-button>
    </el-form>
  </el-drawer>
</template>

<style scoped>
.el-drawer__body {
  padding: 20px;
}
</style>